import { defineStore } from 'pinia';

// 定义工作表数据接口
export interface WorksheetData {
  name: string;
  data: any[];
  columns: any[];
  originalHeaders: string[];
  headerRow?: number;
  dataStartRow?: number;
  dataCount?: number;
  expectedFormat?: any;
}

// 定义Excel存储状态接口
interface ExcelState {
  currentFile: File | null;
  worksheets: WorksheetData[];
  activeTabIndex: number;
  validationErrors: string[];
  uploadHistory: Array<{
    id: string;
    fileName: string;
    uploadTime: Date;
    worksheetCount: number;
  }>;
}

export const useExcelStore = defineStore('excel', {
  state: (): ExcelState => ({
    currentFile: null,
    worksheets: [],
    activeTabIndex: 0,
    validationErrors: [],
    uploadHistory: []
  }),

  getters: {
    // 获取当前激活的工作表
    activeWorksheet: (state) => {
      console.log(state.worksheets,'state.worksheets');
      console.log(state.activeTabIndex,'state.activeTabIndex');
      if (state.worksheets.length > 0) {
        return state.worksheets[state.activeTabIndex];
      }
      return null;
    },
    
    // 获取工作表总数
    worksheetCount: (state) => state.worksheets.length,
    
    // 检查是否有数据校验错误
    hasValidationErrors: (state) => state.validationErrors.length > 0
  },

  actions: {
    // 设置当前上传的文件
    setCurrentFile(file: File | null) {
      this.currentFile = file;
    },

    // 设置工作表数据
    setWorksheets(worksheets: WorksheetData[]) {
      this.worksheets = worksheets;
      this.activeTabIndex = 0;
      
      // 如果有新文件上传，记录到历史
      if (this.currentFile && worksheets.length > 0) {
        this.addToHistory({
          fileName: this.currentFile.name,
          worksheetCount: worksheets.length
        });
      }
    },

    // 设置当前激活的标签页索引
    setActiveTabIndex(index: number) {
      console.log(index,'index');
      this.activeTabIndex = index;
    },

    // 设置数据校验错误
    setValidationErrors(errors: string[]) {
      this.validationErrors = errors;
    },

    // 添加到上传历史
    addToHistory(data: {
      fileName: string;
      worksheetCount: number;
    }) {
      const historyItem = {
        id: Date.now().toString(),
        fileName: data.fileName,
        uploadTime: new Date(),
        worksheetCount: data.worksheetCount
      };
      
      // 添加到历史记录的开头
      this.uploadHistory.unshift(historyItem);
      
      // 限制历史记录数量为10条
      if (this.uploadHistory.length > 10) {
        this.uploadHistory.pop();
      }
    },

    // 清空所有数据
    clearAll() {
      this.currentFile = null;
      this.worksheets = [];
      this.activeTabIndex = 0;
      this.validationErrors = [];
    },

    // 根据ID获取历史记录中的文件
    getHistoryItemById(id: string) {
      return this.uploadHistory.find(item => item.id === id);
    }
  }
});